package com.woniu.service.impl;

import com.woniu.entity.Result;
import com.woniu.entity.dto.UserLoginDTO;
import com.woniu.mapper.UserMapper;
import com.woniu.pojo.User;
import com.woniu.service.IUserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @author tarnett
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User getByOpenId(String openId) {
        return userMapper.getByOpenId(openId);
    }

    @Override
    public User getByAccount(String account) {
        return userMapper.getByAccount(account);
    }

    @Override
    public Result register(UserLoginDTO userLoginDTO) {
        // 判断账号是否已经被注册
        User user1 = getByAccount(userLoginDTO.getAccount());
        if(user1 != null){
            return Result.error("该账号已经被注册");
        }
        // 对密码进行加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(userLoginDTO.getPassword());
        // 进行注册操作
        User user = new User();
        user.setAccount(userLoginDTO.getAccount());
        user.setPassword(newPassword);
        user.setType("0");
        if(!StringUtils.isEmpty(userLoginDTO.getOpenId())){
            user.setOpenId(userLoginDTO.getOpenId());
        }
        userMapper.save(user);
        // 返回数据
        return Result.ok();
    }

    @Override
    public void updateOpenIdByAccount(String openId, String account) {
        userMapper.updateOpenIdByAccount(openId, account);
    }
}
